<template>
  <view class="history-page">
    <!-- 1. 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="back">←</view>
      <view class="nav-title">聆听历史</view>
      <view class="empty"></view>
    </view>

    <!-- 2. 时间筛选栏 -->
    <view class="time-filter-bar">
      <view 
        class="time-filter-item" 
        :class="activeTime === 'week' ? 'filter-active' : ''"
        @click="switchTime('week')"
      >
        近一周
      </view>
      <view 
        class="time-filter-item" 
        :class="activeTime === 'month' ? 'filter-active' : ''"
        @click="switchTime('month')"
      >
        近一月
      </view>
      <!-- 播放统计快捷入口 -->
      <view class="stats-entry" @click="showStats">
        播放统计
      </view>
    </view>

    <!-- 3. 听歌历史列表区（直接排布，无日期分组） -->
    <view class="history-list">
      <!-- 加载中状态 -->
      <view class="loading" v-if="loading">
        <view class="loading-icon">●</view>
        <view class="loading-text">加载聆听历史中...</view>
      </view>

      <!-- 无历史记录状态 -->
      <view class="empty-history" v-else-if="filteredHistory.length === 0">
        <image src="/static/empty-history.png" class="empty-img" mode="widthFix"></image>
        <view class="empty-text">暂无聆听历史</view>
        <view class="empty-tip">去发现更多喜欢的歌曲吧~</view>
      </view>

      <!-- 听歌历史列表（直接渲染，不分组） -->
      <view v-else>
        <view 
          class="song-item" 
          v-for="(item, idx) in filteredHistory" 
          :key="item.id"
        >
          <!-- 歌曲封面+信息区 -->
          <view class="item-info">
            <image :src="item.coverUrl" class="item-cover"></image>
            <view class="info-text">
              <view class="song-title">{{item.title}}</view>
              <view class="song-meta">
                <view class="play-time">
                  {{ formatPlayTime(item.playTime) }}
                </view>
              </view>
            </view>
          </view>

          <!-- 功能按钮区（播放+收藏） -->
          <view class="item-btns">
            <view 
              class="play-btn" 
              @click="togglePlay(item)"
              :class="{ 'pause-btn': currentPlayId === item.id && isPlaying }"
            >
              {{ currentPlayId === item.id && isPlaying ? '■' : '▶' }}
            </view>
            <view 
              class="collect-btn" 
              :class="{ 'collected': item.isCancel===0 }"
              @click="toggleCollect(item)"
            >
              {{ item.isCancel===0? '♥' : '♡' }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 音频播放进度条（播放时显示） -->
    <view class="audio-progress" v-if="currentPlayId !== -1">
      <view class="progress-bar" :style="{ width: progress + '%' }"></view>
    </view>

    <!-- 播放统计弹窗 -->
    <view class="stats-modal" v-if="showStatsModal">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">{{ activeTime === 'week' ? '近一周' : '近一月' }}播放统计</view>
          <view class="close-btn" @click="showStatsModal = false">×</view>
        </view>
        <view class="stats-content">
          <view class="stats-item">
            <view class="stats-label">总播放次数</view>
            <view class="stats-value">{{ stats.totalPlays }}</view>
          </view>
          <view class="stats-item">
            <view class="stats-label">播放歌曲数</view>
            <view class="stats-value">{{ stats.totalSongs }}</view>
          </view>
          <view class="stats-item">
            <view class="stats-label">最爱歌手</view>
            <view class="stats-value">{{ stats.topSinger || '暂无' }}</view>
          </view>
          <view class="stats-item">
            <view class="stats-label">播放时长</view>
            <view class="stats-value">{{ formatDuration(stats.totalDuration) }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 引入真实接口（请根据实际项目路径调整）

import { collectMusic } from '../../../api/User';
import { addListeningHistory, getListenHistory } from '../../../api/listeningHistory';

export default {
  onLoad() {
    this.loading = true;
    // 初始化音频播放器
    this.initAudio();
    // 默认加载近一周历史
    this.switchTime('week')
      .finally(() => {
        this.loading = false;
      });
  },

  onUnload() {
    // 页面销毁时清理音频实例和计时器
    if (this.audioContext) {
      this.audioContext.stop();
      this.audioContext.destroy();
      this.audioContext = null;
    }
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
      this.progressTimer = null;
    }
  },

  data() {
    return {
      loading: false,
      activeTime: 'week', 
      allHistory: [], 
      filteredHistory: [], 
      currentPlayId: -1, 
      isPlaying: false, 
      audioContext: null, 
      progress: 0, 
      progressTimer: null, 
      showStatsModal: false, 
      stats: { 
        totalPlays: 0,
        totalSongs: 0,
        topSinger: '',
        totalDuration: 0
      }
    };
  },
  methods: {
    // 返回上一页
    back() {
      uni.switchTab({ url: "/pages/myHome/myHome" });
    },

    /**
     * 切换时间范围（近一周/近一月）
     * @param {string} timeType - 时间类型（week/month）
     */
    switchTime(timeType) {
      this.activeTime = timeType;
      this.loading = true;
      
      return getListenHistory(timeType)
        .then(res => {
          if (res.code === 0 && res.data) {
            // 按播放时间倒序排列（最新播放在前）
            this.allHistory = res.data.sort((a, b) => new Date(b.playTime) - new Date(a.playTime));
            this.filteredHistory = [...this.allHistory];
            // 获取对应时间范围的播放统计
            this.getListenStats(timeType);
          } else {
            this.allHistory = [];
            this.filteredHistory = [];
            uni.showToast({ title: res.msg || '获取历史失败', icon: 'none' });
          }
        })
        .catch(err => {
          console.error('获取听歌历史失败:', err);
          this.allHistory = [];
          this.filteredHistory = [];
          uni.showToast({ title: '网络异常，请重试', icon: 'none' });
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 获取播放统计数据
     * @param {string} timeType - 时间类型（week/month）
     */
    getListenStats(timeType) {
   
    },

    // 显示播放统计弹窗
    showStats() {
      // 若未获取到统计数据，先触发一次获取
      if (this.stats.totalPlays === 0) {
        this.getListenStats(this.activeTime);
      }
      this.showStatsModal = true;
    },

    // 初始化音频播放器
    initAudio() {
      this.audioContext = uni.createInnerAudioContext();
      this.audioContext.loop = false; 
      this.audioContext.autoplay = false;
      // 音频事件监听
      this.audioContext.onPlay(() => {
        this.isPlaying = true;
        this.startProgressTimer();
      });
      this.audioContext.onPause(() => {
        this.isPlaying = false;
        this.stopProgressTimer();
      });
      this.audioContext.onTimeUpdate(() => {
        if (this.audioContext.duration > 0) {
          this.progress = Math.floor((this.audioContext.currentTime / this.audioContext.duration) * 100);
        }
      });
      this.audioContext.onEnded(() => {
        this.isPlaying = false;
        this.currentPlayId = -1;
        this.progress = 0;
        this.stopProgressTimer();
        uni.showToast({ title: '播放结束', icon: 'none' });
      });
      this.audioContext.onError((err) => {
        this.isPlaying = false;
        this.currentPlayId = -1;
        this.progress = 0;
        this.stopProgressTimer();
        uni.showToast({ title: `播放失败: ${err.errMsg}`, icon: "none" });
      });
    },
    
    // 启动进度条计时器
    startProgressTimer() {
      this.stopProgressTimer();
      this.progressTimer = setInterval(() => {
        if (this.progress < 100) {
          this.progress += 0.5;
        } else {
          this.progress = 100;
          this.stopProgressTimer();
          this.isPlaying = false;
          this.currentPlayId = -1;
          uni.showToast({ title: '播放结束', icon: 'none' });
        }
      }, 300);
    },

    // 停止播放进度计时器
    stopProgressTimer() {
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
        this.progressTimer = null;
      }
    },

    /**
     * 播放/暂停歌曲
     * @param {object} item - 歌曲数据（包含id、audioUrl等字段）
     */
    togglePlay(item) {
      if (!this.audioContext) this.initAudio();

      if (this.currentPlayId === item.id) {
        // 同一首歌：切换播放/暂停
        this.isPlaying ? this.audioContext.pause() : this.audioContext.play();
      } else {
        // 不同歌曲：播放新歌曲
        if (!item.audioUrl) {
          uni.showToast({ title: '音频地址无效', icon: 'none' });
          return;
        }
        this.currentPlayId = item.id;
        this.progress = 0;
        this.audioContext.stop();
        this.audioContext.src = item.audioUrl.trim();
        // 尝试播放，失败时提示
        this.audioContext.play().catch(err => {
          console.error("播放失败:", err);
          uni.showToast({ title: '音频资源暂不可用', icon: 'none' });
          this.isPlaying = false;
          this.currentPlayId = -1;
        });
      }
    },

    /**
     * 收藏/取消收藏歌曲
     * @param {object} item - 歌曲数据（包含id、isCollected等字段）
     */
    toggleCollect(item) {
      collectMusic(item.id) 
        .then(res => {
          if (res.code === 0) {
            let toastMsg = res.data; 
            if (res.data.includes("取消")) {
              item.isCancel = 1;
            } else {
              item.isCancel = 0;
            }
            uni.showToast({ title: toastMsg, icon: 'none' });
          } else {
            uni.showToast({ title: res.data || '操作失败，请重试', icon: 'none' });
          }
        })
    },

    /**
     * 格式化播放时间（仅保留时分，如：14:30）
     * @param {string} timeStr - 原始时间字符串（如：2024-05-20 14:30:25）
     * @returns {string} 格式化后的时间
     */
    formatPlayTime(timeStr) {
      if (!timeStr) return '';
      return timeStr.slice(5,10)+' '+timeStr.slice(11,16);
    },

    /**
     * 格式化播放时长（秒 → 小时:分钟:秒）
     * @param {number} seconds - 总秒数
     * @returns {string} 格式化后的时长
     */
    formatDuration(seconds) {
      if (seconds <= 0) return '0秒';
      const h = Math.floor(seconds / 3600);
      const m = Math.floor((seconds % 3600) / 60);
      const s = seconds % 60;
      const parts = [];
      if (h > 0) parts.push(`${h}小时`);
      if (m > 0) parts.push(`${m}分`);
      parts.push(`${s}秒`);
      return parts.join('');
    }
  }
};
</script>

<style scoped>
.history-page {
  background: #ffffff;
  min-height: 100vh;
  padding-bottom: 30rpx;
}

/* 1. 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 100rpx;
  background: #ffffff;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #2d4263;
}
.back-btn {
  font-size: 36rpx;
  color: #2d4263;
  cursor: pointer;
}
.empty {
  width: 36rpx;
}

/* 2. 时间筛选栏 */
.time-filter-bar {
  display: flex;
  align-items: center;
  background: #ffffff;
  padding: 0 20rpx;
  height: 80rpx;
  box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.03);
  justify-content: space-between;
}
.time-filter-item {
  font-size: 26rpx;
  color: #6c8aa8;
  padding: 8rpx 25rpx;
  border-radius: 20rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}
.filter-active {
  background: #e8f3ff;
  color: #7bb3e6;
  font-weight: 500;
}
.stats-entry {
  font-size: 24rpx;
  color: #7bb3e6;
  cursor: pointer;
  padding: 8rpx 15rpx;
  border-radius: 15rpx;
  transition: background 0.2s ease;
}
.stats-entry:hover {
  background: #e8f3ff;
}

/* 3. 听歌历史列表容器 */
.history-list {
  padding: 20rpx;
}

/* 加载中样式 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 150rpx 0;
}
.loading-icon {
  font-size: 40rpx;
  color: #7bb3e6;
  animation: spin 1.5s linear infinite;
  margin-bottom: 20rpx;
}
.loading-text {
  font-size: 26rpx;
  color: #6c8aa8;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 无历史记录样式 */
.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}
.empty-img {
  width: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.7;
}
.empty-text {
  font-size: 28rpx;
  color: #2d4263;
  margin-bottom: 15rpx;
}
.empty-tip {
  font-size: 24rpx;
  color: #a8c3e0;
}

/* 歌曲列表项（删除日期分组相关样式） */
.song-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 25rpx 30rpx;
  margin-bottom: 18rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}
.song-item:hover {
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
}

/* 歌曲信息区 */
.item-info {
  display: flex;
  align-items: center;
  flex: 1;
}
.item-cover {
  width: 100rpx;
  height: 100rpx;
  border-radius: 16rpx;
  object-fit: cover;
  border: 2rpx solid #f0f0f0;
}
.info-text {
  margin-left: 25rpx;
  min-width: 0;
}
.song-title {
  font-size: 28rpx;
  color: #2d4263;
  font-weight: 500;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.song-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 22rpx;
  color: #6c8aa8;
}
.song-singer {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.play-time {
  display: flex;
  align-items: center;
  gap: 8rpx;
}
.play-time::before {
  content: "🔊";
  font-size: 20rpx;
}

/* 功能按钮区 */
.item-btns {
  display: flex;
  align-items: center;
  gap: 30rpx;
}
.play-btn {
  width: 56rpx;
  height: 56rpx;
  background: #e8f3ff;
  color: #7bb3e6;
  border-radius: 50%;
  text-align: center;
  line-height: 56rpx;
  font-size: 24rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}
.pause-btn {
  background: #7bb3e6;
  color: #ffffff;
}
.play-btn:hover {
  transform: scale(1.05);
}
.collect-btn {
  font-size: 36rpx;
  color: #a8c3e0;
  cursor: pointer;
  transition: all 0.2s ease;
}
.collected {
  color: #ff8a9a; 
  animation: pulse 0.5s ease;
}
.collect-btn:hover {
  transform: scale(1.1);
}
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

/* 音频播放进度条 */
.audio-progress {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 6rpx;
  background: #f0f0f0;
  z-index: 999;
}
.progress-bar {
  height: 100%;
  background: #7bb3e6;
  transition: width 0.1s linear;
}

/* 播放统计弹窗 */
.stats-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal-content {
  width: 80%;
  max-width: 500rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 35rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  position: relative;
  animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
  0% { opacity: 0; transform: translateY(-20rpx); }
  100% { opacity: 1; transform: translateY(0); }
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}
.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #2d4263;
}
.close-btn {
  font-size: 36rpx;
  color: #6c8aa8;
  cursor: pointer;
  transition: color 0.2s ease;
}
.close-btn:hover {
  color: #7bb3e6;
}
.stats-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
}
.stats-item {
  background: #f9f9f9;
  border-radius: 16rpx;
  padding: 25rpx;
  text-align: center;
  transition: transform 0.2s ease;
}
.stats-item:hover {
  transform: translateY(-5rpx);
}
.stats-label {
  font-size: 24rpx;
  color: #6c8aa8;
  margin-bottom: 15rpx;
}
.stats-value {
  font-size: 34rpx;
  font-weight: 700;
  color: #7bb3e6;
}

/* 适配小屏设备（320px以下） */
@media (max-width: 320px) {
  .time-filter-item {
    font-size: 24rpx;
    padding: 8rpx 20rpx;
  }
  .song-title {
    font-size: 26rpx;
  }
  .song-meta {
    font-size: 20rpx;
  }
  .item-cover {
    width: 90rpx;
    height: 90rpx;
  }
  .stats-content {
    grid-template-columns: 1fr;
  }
}

/* 适配中屏设备（320px-414px） */
@media (min-width: 321px) and (max-width: 414px) {
  .stats-content {
    gap: 25rpx;
  }
  .stats-item {
    padding: 20rpx;
  }
  .stats-value {
    font-size: 32rpx;
  }
}
</style>